<?php

namespace App\Http\Controllers\Company;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Models\ClassCourseModel;
use App\Models\ClassStudentModel;
use App\Models\CourseArrangeModel;

class ClassCourseController extends Controller
{
    public function list(Request $request) {
        $classId = $request->input('class_id');
        $courses = ClassCourseModel::where('class_id', $classId)->get();
        return self::ok($courses);
    }
    public function add(Request $request) {
        
        $classId = $request->input('class_id');
        $teacherId = $request->input('teacher_id');
        $teacherName = $request->input('teacher_name');
        $courseId = $request->input('course_id');

        if (!$classId) {
            return self::err('请选择班级');
        }
        if (!$courseId) {
            return self::err('请选择课程');
        }
        if (!$teacherId) {
            return self::err('请选择教师');
        }

        $id = $request->input('id', 0);
        if ($id) { // 替换老师的操作
            ClassCourseModel::where('id', $id)->update([
                'teacher_id' => $teacherId,
                'teacher_name' => $teacherName,
            ]);

            // 把所有排课的老师也替换
            CourseArrangeModel::where([
                'class_id' => $classId,
                'course_id' => $courseId,
            ])->where('date', '>=', date('Y-m-d'))->update([
                'teacher_id' => $teacherId,
            ]);
            return self::ok();
        }

        // 检查该班级是否已经存在该课程
        $existingClassCourse = ClassCourseModel::where('class_id', $classId)
            ->where('course_id', $courseId)
            ->first();
        if ($existingClassCourse) {
            return self::err('本班级已经存在该课程');
        }
        $classCourse = new ClassCourseModel();
        $classCourse->fill($request->only('class_id', 'course_id', 'course_name', 'teacher_id', 'teacher_name'));
        $classCourse->save();
        return self::ok();
    }

    public function delete(Request $request) {
        $classCourse = ClassCourseModel::find($request->input('id'));
        if (!$classCourse) {
            return self::err('课程不存在');
        }

        // 如果班级课程下面有学生，不能删除
        $hasStudent = ClassStudentModel::where('course_id', $classCourse->course_id)
        ->where('class_id', $classCourse->class_id)
        ->first();
        if ($hasStudent) {
            return self::err('该课程下面有学员，先移除学员，再删除课程');
        }

        $classCourse->delete();

        // 删除排课
        CourseArrangeModel::where('class_course_id', $classCourse->id)->delete();
        return self::ok();
    }
}
